package com.pactera.miyuangroup.filter;

import com.alibaba.fastjson.JSON;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.service.LoginUserService;
import com.pactera.miyuangroup.util.JwtUtils;
import com.pactera.miyuangroup.vo.response.ResultModel;
import com.pactera.miyuangroup.vo.response.ResultStatusCode;
import com.pactera.miyuangroup.vo.response.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Base64;

/**
 * 自定义解析器实现参数绑定
 *
 * @author Wangwu
 * @create 2018-04-13 下午2:03
 **/
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private RedisOperation redis;
    private LoginUserService loginUserService;

    public CurrentUserMethodArgumentResolver(RedisOperation redis,LoginUserService loginUserService) {
        this.redis = redis;
        this.loginUserService = loginUserService;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {
        String header = nativeWebRequest.getHeader("Authorization");
        try {
            //获取redis token
            String token = redis.get(Constants.REDIS_AUTHORIZATION_TOKEN + header, String.class, "");
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //还原jwt token
            token = new String(Base64.getDecoder().decode(token), "utf-8");
            if (token != null || token.startsWith(JwtUtils.getAuthorizationHeaderPrefix())) {
                token = token.replace(JwtUtils.getAuthorizationHeaderPrefix(), "");
                String id = JwtUtils.getJwtById(token);
                User user = loginUserService.selectLoginInfoById(id);
                return user;
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
